
`include "defines.v"

module reg_file (
    input  wire              clk,
    input  wire              rst,

    input  wire [4 :      0] w_addr,
    input  wire [`BUS_WIDTH] w_data,
    input  wire              reg_wen,

    input  wire [4 :      0] r_addr1,
    output reg  [`BUS_WIDTH] r_data1,

    input  wire [4 :      0] r_addr2,
    output reg  [`BUS_WIDTH] r_data2,

    output wire [`BUS_WIDTH] regs_o[0 : 31]    // difftest
);


    reg [`BUS_WIDTH] regs[0 : 31];

    always @(posedge clk) begin    // 寄存器写入
        if (rst) begin   
            regs[0]  <= `ZERO_WORD;
			regs[1]  <= `ZERO_WORD;
			regs[2]  <= `ZERO_WORD;
			regs[3]  <= `ZERO_WORD;
			regs[4]  <= `ZERO_WORD;
			regs[5]  <= `ZERO_WORD;
			regs[6]  <= `ZERO_WORD;
			regs[7]  <= `ZERO_WORD;
			regs[8]  <= `ZERO_WORD;
			regs[9]  <= `ZERO_WORD;
			regs[10] <= `ZERO_WORD;
			regs[11] <= `ZERO_WORD;
			regs[12] <= `ZERO_WORD;
			regs[13] <= `ZERO_WORD;
			regs[14] <= `ZERO_WORD;
			regs[15] <= `ZERO_WORD;
			regs[16] <= `ZERO_WORD;
			regs[17] <= `ZERO_WORD;
			regs[18] <= `ZERO_WORD;
			regs[19] <= `ZERO_WORD;
			regs[20] <= `ZERO_WORD;
			regs[21] <= `ZERO_WORD;
			regs[22] <= `ZERO_WORD;
			regs[23] <= `ZERO_WORD;
			regs[24] <= `ZERO_WORD;
			regs[25] <= `ZERO_WORD;
			regs[26] <= `ZERO_WORD;
			regs[27] <= `ZERO_WORD;
			regs[28] <= `ZERO_WORD;
			regs[29] <= `ZERO_WORD;
			regs[30] <= `ZERO_WORD;
			regs[31] <= `ZERO_WORD;
        end
        else begin
            if ((reg_wen == 1'b1) && (w_addr != 5'b0)) begin    // x0寄存器不能改写
                regs[w_addr] <= w_data;
            end
        end
    end

    always @(*) begin    // 寄存器读出
        if (rst == 1'b1) begin
            r_data1 = `ZERO_WORD;
			r_data2 = `ZERO_WORD;
        end
        else begin
            r_data1 = regs[r_addr1];
			r_data2 = regs[r_addr2];
        end
    end

	genvar i;
	generate
		for (i = 0; i < 32; i = i + 1) begin    // 寄存器状态提交
			assign regs_o[i] = (reg_wen & (w_addr == i) & (i != 0)) ? w_data : regs[i];
		end
	endgenerate
    

endmodule
